package com.atguigu.gmall.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.user.vo.LoginSuccessVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.user.entity.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public LoginSuccessVo login(UserInfo userInfo) {
        //获取前端传来的数据
        String loginName = userInfo.getLoginName();
        String passwd = MD5.encrypt(userInfo.getPasswd());//明文 ==> 加密
        //数据库查询用户是否存在
        UserInfo entity = lambdaQuery()
                .eq(UserInfo::getLoginName, loginName)
                .eq(UserInfo::getPasswd, passwd)
                .one();

        //用户不存在
        if (entity == null){
            //全局返回异常
            throw new GmallException(ResultCodeEnum.LOGIN_ERROR);
        }
        //用户存在
        LoginSuccessVo loginSuccessVo = new LoginSuccessVo();
        loginSuccessVo.setUserId(entity.getId());
        loginSuccessVo.setNickName(entity.getNickName());

        //令牌 token
        String token = UUID.randomUUID().toString().replace("_", "");
        loginSuccessVo.setToken(token);

        //用户信息存入reids，各个服务器之间可以共享
        redisTemplate.opsForValue().set(RedisConst.LOGIN_USER+token, JSON.toJSONString(entity), 7, TimeUnit.DAYS);

        //返回前端需要的数据 json
        return loginSuccessVo;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(RedisConst.LOGIN_USER + token);
    }
}




